package UserThread;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.SystemClock;
import android.util.Log;
import android.view.Gravity;

import androidx.annotation.RequiresApi;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import UserAdapter.ChatAdapter;
import UserClientSocket.Client;
import UserGlobal.GlobalData;

//好友消息接收线程
public class ChatMesRecieveThread extends Thread {
    Runnable mAction = null;
    Activity mActivity = null;
    Boolean isInterrupted = false;
    Client mClient = new Client();
    public ChatMesRecieveThread(Activity a, Runnable b) {
        mActivity = a;
        mAction = b;
    }
    public void setAction(Runnable a, Activity b) {
        mActivity = b;
        mAction = a;
    }
    @Override
    public void interrupt() {
        isInterrupted = true;
        mClient.close();
    }
    //前台模式
    void setForeMode() {
        int count=0;
        if (GlobalData.Myid.length() != 0) {
            try {
                Log.d("socket", "客户端打开成功");
                SocketChannel sc = SocketChannel.open();
                sc.configureBlocking(false);
                    Boolean bool = sc.connect(new InetSocketAddress(GlobalData.Serverip, 6000));
                    final Selector mSelector = Selector.open();
                    sc.register(mSelector, SelectionKey.OP_CONNECT);
                    while (true){
                        if(mSelector.select(5000)>0){
                            Iterator<SelectionKey> mIterator = mSelector.selectedKeys().iterator();
                            while (mIterator.hasNext()) {
                                final SelectionKey sk = mIterator.next();
                                if (sk.isConnectable()) {
                                    SocketChannel c = (SocketChannel) sk.channel();
                                    if (c.finishConnect()) {
                                        Log.d("socket", "服务器连接成功");
                                    } else {
                                        Log.d("socket", "服务器连接失败");
                                    }
                                    c.register(mSelector, SelectionKey.OP_WRITE);
                                } else if (sk.isWritable()) {
                                    Log.d("socket", "开始写入数据");
                                    try {
                                        final SocketChannel c = (SocketChannel) sk.channel();
                                        ByteBuffer buf = ByteBuffer.allocate(GlobalData.Myid.getBytes().length);
                                        buf.limit(GlobalData.Myid.getBytes().length);
                                        buf.put(GlobalData.Myid.getBytes());
                                        buf.flip();
                                        while (buf.hasRemaining())
                                            c.write(buf);
                                        Log.d("socket", "数据已发送到服务器");
                                        c.register(mSelector, SelectionKey.OP_READ);
                                    } catch (SocketException e) {
                                        sk.cancel();
                                        Log.d("socket", "服务器重置");
                                    }
                                }else if (sk.isReadable()){
                                    Log.d("socket", "开始读取数据");
                                    try {
                                        SocketChannel c = (SocketChannel) sk.channel();
                                        ByteBuffer buf = ByteBuffer.allocate(512);
                                        int i=0;
                                        while((i=c.read(buf))<=0);
                                        buf.limit(i);
                                        while (buf.hasRemaining())c.read(buf);
                                        buf.flip();
                                        String receiverid = new String(Arrays.copyOf(buf.array(),buf.limit()));
                                        if(!receiverid.equals(".********.")){
                                            int ind=receiverid.indexOf("-");
                                            if(ind!=-1){
                                                String sender =receiverid.substring(0,ind);
                                                String mes=receiverid.substring(ind+1,receiverid.length());
                                                count++;
                                                Log.d("socketreceive", "接收" + sender + "发的的第" + count + "条消息----" + mes);
                                                int index = GlobalData.mHistoryId.indexOf(sender);
                                                Map<Integer, String> map = new HashMap<>();
                                                map.put(Gravity.LEFT, mes);
                                                if (index == -1) {
                                                    GlobalData.mHistoryId.add(sender);
                                                    ArrayList<Map<Integer, String>> mGravityList = new ArrayList<>();
                                                    GlobalData.mChatHistory.add(mGravityList);
                                                }
                                                index = GlobalData.mHistoryId.indexOf(sender);
                                                GlobalData.mChatHistory.get(index).add(map);
                                                if(GlobalData.action!=null)
                                                    GlobalData.activity.runOnUiThread(GlobalData.action);//提交消息更新UI线程
                                            }
                                        }
                                        c.register(mSelector, SelectionKey.OP_WRITE);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                                mIterator.remove();
                            }
                        }
                    }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void run() {
        setForeMode();
    }
}

